import axios from 'axios'
import jsonBig from 'json-bigint';
import router from '../router';
import { ElMessage } from 'element-plus';
// 创建axios实例
// 创建请求时可以用的配置选项

// 配后端数据的接收方式application/json;charset=UTF-8或者application/x-www-form-urlencoded;charset=UTF-8
const contentType = 'application/json;charset=UTF-8'

// var base = '/api';
var base = 'http://nrp.yugaosu.com/supermap';
const JSONbigToString = jsonBig({ storeAsString: true });
const instance = axios.create({
	/**
	 * 是否携带cookie,注意若携带cookie后端必须配置
	 * 1.Access-Control-Allow-Origin为单一域名(具体到IP + port,用localhost貌似不行)
	 * 2.需要带上响应头Access-Control-Allow-Credentials
	 */
	// withCredentials: true,
	timeout: 20000,
	baseURL: base,
	// baseURL: 'http://192.168.10.233:8081',
	headers: {
		'Content-Type': contentType
	},
	transformResponse: [
		function (data) {
			try {
				// console.log(JSONbigToString.parse(data));
				return JSONbigToString.parse(data)
			} catch (err) {
				return data;
			}
			
		}
	]
})
// axios的全局配置
instance.defaults.headers.post = {
	'Content-Type': 'application/json'
}
instance.defaults.headers.common = {
	'Auth-Type': 'company-web',
	'X-Requested-With': 'XMLHttpRequest',
	token: 'sdfjlsdfjlsdjflsjflsfjlskd'
}
// instance.defaults.headers['Content-Type'] = "text/event-stream; charset=utf-8";
instance.defaults.headers['Access-Control-Allow-Origin'] = "*";
instance.defaults.headers['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";

// 添加请求拦截器(post只能接受字符串类型数据)
instance.interceptors.request.use(
	config => {
		const token = localStorage.getItem('token');
		if (!token && config.url == '/login/login') {
			return config;
		} else {
			config.headers['token'] = token;
			
			return config;
		}
	},
	error => {
		return Promise.reject(error)
	}
)
const errorHandle = (status, other) => {
	switch (status) {
		case 400:
            console.log('信息校验失败');
			break
		case 401:
			console.log('认证失败');
			break
		case 403:
			console.log('token校验失败');
			break
		case 404:
            console.log('请求的资源不存在');
			break
		default:
            console.log(other);
			break
	}
}

// 添加响应拦截器
instance.interceptors.response.use(
	// 响应包含以下信息data,status,statusText,headers,config
	res => {
		if (res.data && res.data.code !== 0 && !(res.data instanceof Blob)) {
            // console.log(res.data.message || '服务器出错!');
		}
		// 请求通用处理
		errorHandle(res.data.code, res.data)
		return res.data
	},
	err => {
		// console.log(err);
		const { response } = err
		if (response) {
			errorHandle(response.status, response.data)
			return Promise.reject(response)
		}
        // console.log('请求失败');
		return response
	}
)

export default instance;